const { app, BrowserWindow, session } = require('electron')
const path = require('path')

app.whenReady().then(() => {
  createWindow()
  win.loadFile(path.join(__dirname, '../renderer/index.html'))
  win.webContents.openDevTools({ mode: 'bottom' })
})

let win
function createWindow() {
  win = new BrowserWindow({ width: 600, height: 800 })
  customUA()
  simpleCors()
  redirect()
}

// 自定义UA
function customUA() {
  const filter = {
    urls: ['https://*.github.com/*'],
  }
  session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
    details.requestHeaders['User-Agent'] = 'MyAwesomeAgent'
    callback({ requestHeaders: details.requestHeaders })
  })
}

// 绕过跨域限制
function simpleCors() {
  const filter = {
    urls: ['http://localhost:*/*'],
  }
  win.webContents.session.webRequest.onHeadersReceived(filter, (details, callback) => {
    const { responseHeaders } = details
    responseHeaders['Access-Control-Allow-Origin'] = ['*']
    callback({ responseHeaders })
  })
}

// 请求转发
function redirect() {
  win.webContents.session.webRequest.onBeforeRequest(
    {
      urls: [],
    },
    (details, callback) => {
      const { url, resourceType } = details
      const response = { cancel: false }
      if (resourceType === 'xhr' && url.startsWith('http://localhost:3030')) {
        response.redirectURL = 'http://localhost:4040'
      }
      callback(response)
    },
  )
}
